'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');


class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} = this;
        let {username,password,num} = ctx.request.body;
        //容错处理
        if(username && /^\w{4,6}$/.test(password) && num){
            //排重
            let user = await service.user.selectUser(num);
            if(user.length){
                //存在
                ctx.body = {
                    code:3,
                    msg:'此学号存在'
                }
            }else{
                try{
                    //1.用户表  2.用户角色表
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(username,hmcPwd,num);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
        let {ctx,service} = this;
        let {num,password} = ctx.request.body;
        if(num && /^\w{4,6}$/.test(password)){
            let hmcPwd = ctx.helper.hmc(password);
            let user = await service.user.login(num,hmcPwd);
            console.log(user);
            if(user.length){
                //给前端返回一个rid
                let uid = user[0].id;
                let rid = await service.user.getRid(uid);
                console.log("rid-=========",rid)
                let rolename = await service.user.getRolename(rid[0].rid);
                let token = jwt.sign({uid:user[0].id,rid:rid[0].rid,num:user[0].num},'lixd',{expiresIn:60*60})
                
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    uid:user[0].id,
                    username:user[0].username,
                    rolename:rolename[0].role_name,
                    token
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }      
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //查询今天没有录入成绩的人员
    async notAdd(){
        let {ctx,service} = this;
        let userlist = await service.user.notAdd();
        ctx.body = {
            code:1,
            data:userlist
        }
    }
}

module.exports = UserController;
